#!/usr/bin/env python
# encoding: utf-8
"""
__init__.py

Created by Grégoire Détrez on 2009-02-22.
Copyright (c) 2009 __MyCompanyName__. All rights reserved.
"""

import sys
import os
import unittest

from ftbexplorer.core.models import WordTreeNode


class BaseClause(object):
    
    def __init__(self):
        self._free_connector = False
        self._elements = []
    
    def has_free_connector(self):
        return self._free_connector
    
    def __add__(self, other):
        return PartialClause(self, other)
    
    def __unicode__(self):
        unic = u"%s[%s]" % (self.__class__.__name__, ", ".join(map(unicode, self._elements)))
        if self.has_free_connector():
            unic += u"+"
        return unic
        
    def __iter__(self):
        return self._elements.__iter__()
    
    def next(self):
        return self._elements.next()
    

class EmptyClause(BaseClause):
    pass


class Clause(BaseClause):
    
    def __init__(self, partial):
        assert isinstance(partial, PartialClause)
        BaseClause.__init__(self)
        self._free_connector = False
        self._elements = list(partial)
    

class PartialClause(BaseClause):
    
    def __init__(self, *clauses):
        BaseClause.__init__(self)
        for k in clauses:
            assert isinstance(k, BaseClause)
            if isinstance(k, EmptyClause):
                pass
            elif isinstance(k, PartialClause):
                self._elements += list(k)
            else:
                self._elements += [k]
            self._free_connector = self.has_free_connector() or k.has_free_connector()
                

class WordClause(BaseClause):
    def __init__(self, word):
        assert isinstance(word, WordTreeNode)
        BaseClause.__init__(self)
        self._attr = {}
        for k in word.attributes():
            self._attr[k] = word.getattr(k)
        #self._elements = [self]
        self.text = word.get_text()
    
    def __unicode__(self):
        return  self.text 

class ConnectorClause(WordClause):
    def __init__(self, word):
        WordClause.__init__(self, word)
        self._free_connector = True
    
    def __unicode__(self):
        return u"%s" % self.text
    

def Sentence2Clause(sentence):
    return TreeNode2Clause(sentence.tree)

def TreeNode2Clause(node):
    if node.is_word():
        if est_connecteur(node.word()):
            return ConnectorClause(word=node.word())
        else:
            return WordClause(word=node.word())
    fnd = EmptyClause()
    for c in node.children():
        fnd += TreeNode2Clause(c)
    if node.nodeName in ["Ssub", "VPpart"] and fnd.has_free_connector():
        fnd = Clause(fnd)
    return fnd

if __name__ == '__main__':
    unittest.main()
